package com.ztgf.commodity.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityCategoryMapper;
import com.ztgf.commodity.models.bo.CommodityAdminCategoryAddBO;
import com.ztgf.commodity.models.bo.CommodityCategoryBO;
import com.ztgf.commodity.models.bo.CommodityCategorySaveBO;
import com.ztgf.commodity.models.bo.CommodityCategoryUpdateBO;
import com.ztgf.commodity.models.dto.*;
import com.ztgf.commodity.models.service.*;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.PinYinUtils;
import com.ztgf.common.utils.UtilConstants;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.shopping.models.service.shop.IShopCategoryRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * @author: chenyu.wang
 * @date: 2020-05-25 11:20
 * @Description:
 */
@Slf4j
@DubboService
public class CommodityCategoryServiceImpl extends ServiceImpl<CommodityCategoryMapper, CommodityCategoryDTO>
        implements ICommodityCategoryService {

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private ICommodityCategoryFilterRelationService commodityCategoryFilterRelationService;
    @DubboReference
    private ICommodityFilterAttributesService commodityFilterAttributesService;
    @DubboReference
    private ICategoryBrandAttributesRelationService categoryBrandAttributesRelationService;
//    @DubboReference
//    @Lazy
//    private ICommodityInfoService commodityInfoService;
    @Autowired
    private RedisUtil redisUtil;
//    @DubboReference
//    private IBrandInfoService brandInfoService;
    @DubboReference
    private ICommodityUnitService commodityUnitService;
    @DubboReference
    private ICommodityParamService commodityParamService;
    @DubboReference
    private ICommodityParamValueService commodityParamValueService;
    @DubboReference
    private ICommoditySpecificationService commoditySpecificationService;
    @DubboReference
    private ICommoditySpecificationAttrService commoditySpecificationAttrService;
    @DubboReference
    private ICommodityLabelService commodityLabelService;
    @DubboReference
    private IShopCategoryRelationService shopCategoryRelationService;

    @Value("${commodity.shopId}")
    private Long sid;


    @Override
    public List<CommodityCategoryTreeVO> queryCategoryTree() {
        //查询所有类目
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("is_publish", ONE);
        wrapper.orderBy("sort", true);
        List<CommodityCategoryDTO> list = this.selectList(wrapper);
        if (list != null && list.size() > 0) {
            List<CommodityCategoryTreeVO> treeList = new ArrayList<>();
            for (CommodityCategoryDTO dto : list) {
                CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
                treeVO.setId(dto.getId());
                treeVO.setName(dto.getName());
                treeVO.setInitials(dto.getInitials());
                treeVO.setParentId(dto.getParentId());
                treeVO.setSort(dto.getSort());
                treeVO.setCode(dto.getCode());
                treeVO.setIsDisplayNavBar(dto.getIsPublish());
                treeVO.setRate(dto.getDividendScale());
                treeVO.setJdFlag(dto.getJdFlag());
                treeList.add(treeVO);
            }
            List<CommodityCategoryTreeVO> builTree = this.builTree(treeList);
            List<CommodityCategoryTreeVO> realeList = new ArrayList<>();
            //忽略0级不显示
            for (CommodityCategoryTreeVO treeVO : builTree) {
                realeList.addAll(treeVO.getChildList());
            }
            return realeList;
        }
        return null;
    }

    @Override
    public List<CommodityCategoryTreeVO> queryCategoryTree(Long shopId) {
        //查询所有类目
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("is_publish", ONE);
        if(null != shopId || shopId != sid){
            wrapper.eq("jd_flag",ZERO);
        }
        wrapper.orderBy("sort", false);
        List<CommodityCategoryDTO> list = this.selectList(wrapper);
        if (list != null && list.size() > 0) {
            List<CommodityCategoryTreeVO> treeList = new ArrayList<>();
            for (CommodityCategoryDTO dto : list) {
                CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
                treeVO.setId(dto.getId());
                treeVO.setName(dto.getName());
                treeVO.setInitials(dto.getInitials());
                treeVO.setParentId(dto.getParentId());
                treeVO.setSort(dto.getSort());
                treeVO.setCode(dto.getCode());
                treeVO.setIsDisplayNavBar(dto.getIsPublish());
                treeVO.setRate(dto.getDividendScale());
                treeVO.setJdFlag(dto.getJdFlag());
                treeList.add(treeVO);
            }
            List<CommodityCategoryTreeVO> builTree = this.builTree(treeList);
            List<CommodityCategoryTreeVO> realeList = new ArrayList<>();
            //忽略0级不显示
            for (CommodityCategoryTreeVO treeVO : builTree) {
                realeList.addAll(treeVO.getChildList());
            }
            return realeList;
        }
        return null;
    }

    @Override
    public List<CommodityCategoryTreeVO> queryAdminCategoryTree() {
        //查询所有类目
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("sort", true);
        List<CommodityCategoryDTO> list = this.selectList(wrapper);
        if (list != null && list.size() > 0) {
            List<CommodityCategoryTreeVO> treeList = new ArrayList<>();
            for (CommodityCategoryDTO dto : list) {
                CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
                treeVO.setId(dto.getId());
                treeVO.setName(dto.getName());
                treeVO.setInitials(dto.getInitials());
                treeVO.setParentId(dto.getParentId());
                treeVO.setSort(dto.getSort());
                treeVO.setCode(dto.getCode());
                treeVO.setIsDisplayNavBar(dto.getIsPublish());
                treeList.add(treeVO);
            }
            return this.builTree(treeList);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<List<String>> addAdminCategory(CommodityAdminCategoryAddBO bo) {
        log.info("类目添加参数 : {}", bo);
        Result<List<String>> result = new Result<>();
        //先判断该类目父级是否存在类目品牌属性关系，有则删除，只有最低级才能有品牌属性关联
        categoryBrandAttributesRelationService.deleteByCategoryId(bo.getParentId());
        CommodityCategoryDTO insertDTO = new CommodityCategoryDTO();
        Long id = ymlConfig.getPkId();//类目id
        insertDTO.setId(id);
        insertDTO.setCreateUserId(bo.getUserId());//用户id
        insertDTO.setName(bo.getCategoryName());//类目名称
        insertDTO.setInitials(PinYinUtils.getPinYinHeadCharFirstBrand(bo.getCategoryName()));
        insertDTO.setParentId(bo.getParentId());//父id
        insertDTO.setSort(bo.getSort());//排序号
        insertDTO.setCode(UtilConstants.getlinkNo());//唯一标识
        insertDTO.setIsPublish(bo.getIsDisplayNavBar());//是否显示在导航栏 0不显示，1显示
        boolean insert = this.insert(insertDTO);
        if (!insert) {
            result.setCode(CodeEnum.FAIL_100007.getCode());
            result.setMsg(CodeEnum.FAIL_100007.getMsg());
            return result;
        }
        if (bo.getParentId() == ZERO) {
            //添加筛选属性
            if (StringUtils.isNotBlank(bo.getFilterIds())) {
                commodityCategoryFilterRelationService.add(id, bo.getFilterIds());
            }
        } else {
            //参数属性、销售属性、单位
            if (StringUtils.isNotBlank(bo.getBrandList())) {
                List<CategoryBrandAttributesRelationDTO> list = JSONObject.parseArray(bo.getBrandList(), CategoryBrandAttributesRelationDTO.class);
                List<CategoryBrandAttributesRelationDTO> addList = new ArrayList<>();
                for (CategoryBrandAttributesRelationDTO dto : list) {
                    log.info("类目添加属性参数 : {}", dto);
                    CategoryBrandAttributesRelationDTO addDto = new CategoryBrandAttributesRelationDTO();
                    addDto.setId(ymlConfig.getPkId());
                    addDto.setCategoryId(id);
                    addDto.setBrandId(dto.getBrandId());
                    if (StringUtils.isNotBlank(dto.getSpecificationIds())) {
                        addDto.setSpecificationIds(dto.getSpecificationIds());
                    }
                    if (StringUtils.isNotBlank(dto.getParamIds())) {
                        addDto.setParamIds(dto.getParamIds());
                    }
                    if (StringUtils.isNotBlank(dto.getUnitIds())) {
                        addDto.setUnitIds(dto.getUnitIds());
                    }
                    addList.add(addDto);
                }
                categoryBrandAttributesRelationService.insertBatch(addList);
            }
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    @Override
    public CommodityAdminCategoryDetailsVO getAdminDetailsById(Long id) {
        return baseMapper.getAdminDetailsById(id);
    }

    @Override
    public Page<CommodityCategoryBrokerageVO> queryAdminBrokerageList(CommodityCategoryBO bo) {
        Page<CommodityCategoryBrokerageVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityCategoryBrokerageVO> list = baseMapper.queryAdminBrokerageList(page, bo);
        page.setRecords(list);
        return page;
    }

    @Override
    //@Transactional
    public boolean updateTechnicalServiceRatesInBatches(String ids, BigDecimal num,String date) {
        List<CommodityCategoryDTO> list = new ArrayList<>();
        if (!StringUtils.isNotBlank(ids)) {
            return false;
        }
        Long now_m = System.currentTimeMillis(); //获取当前时间毫秒数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date effectiveTime = simpleDateFormat.parse(date);
            Long now_s = effectiveTime.getTime(); //获取生效时间毫秒数
            if (now_m > now_s){                     //立即生效
                String[] split = ids.split(",");
                for (String id : split) {
                    CommodityCategoryDTO dto = new CommodityCategoryDTO();
                    dto.setId(Long.valueOf(id));
                    dto.setEffectiveStatus (0);
                    dto.setEffectiveTime (effectiveTime);
                    dto.setDividendScale(num);
                    list.add(dto);
                }
                shopCategoryRelationService.updateShopDividendScaleByCategory (ids,num);
            }else {                         //通过定时任务生效
                String[] split = ids.split(",");
                for (String id : split) {
                    CommodityCategoryDTO dto = new CommodityCategoryDTO();
                    dto.setId(Long.valueOf(id));
                    dto.setEffectiveStatus (1);
                    dto.setEffectiveTime (effectiveTime);
                    dto.setFutureDividendScale (num);
                    list.add(dto);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace ();
        }
        return this.updateBatchById(list);
    }

    @Override
    public boolean updateEffectiveTime(String ids, String date) {
        List<CommodityCategoryDTO> list = new ArrayList<>();
        if (!StringUtils.isNotBlank(ids)) {
            return false;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date realDate = simpleDateFormat.parse(date);
            String[] split = ids.split(",");
            for (String id : split) {
                CommodityCategoryDTO dto = new CommodityCategoryDTO();
                dto.setId(Long.valueOf(id));
                dto.setEffectiveTime(realDate);
                list.add(dto);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return this.updateBatchById(list);
    }

    @Override
    public boolean updateDividendScaleInBatches(CommodityCategoryUpdateBO bo) {
        List<CommodityCategoryDTO> list = new ArrayList<>();

        String[] split = bo.getIds().split(",");

        for (String id : split) {
            CommodityCategoryDTO dto = new CommodityCategoryDTO();
            dto.setId(Long.valueOf(id));

            if (bo.getType().equals(0)) {
                dto.setDividendScale(bo.getDividendScale());
                dto.setFutureDividendScale(bo.getDividendScale());
            } else {
                dto.setFutureDividendScale(bo.getDividendScale());
                dto.setEffectiveTime(bo.getEffectiveTime());
                dto.setEffectiveStatus(1);//生效状态 0未启动，1启动中 默认0
            }

            list.add(dto);
        }
        return this.updateBatchById(list);
    }

    @Override
    public List<CommodityCategoryTreeVO> queryNewCategoryTree(Long shopId) {
        //从redis中获取类目树
        Object o = redisUtil.get(CATEGORY_REDIS_KEY);
        List<CommodityCategoryTreeVO> list = JSONObject.parseArray(JSONObject.toJSONString(o), CommodityCategoryTreeVO.class);
        List<CommodityCategoryTreeVO> newList = new ArrayList<CommodityCategoryTreeVO>();
        if (!isNull(list)) {
            log.info("shopId------------------------------------------"+shopId);
            log.info("sid------------------------------------------"+sid);



            if(null != shopId && shopId.longValue() != sid.longValue()){
                log.info("11111------------------------------------------"+o.toString());
                for(CommodityCategoryTreeVO vo : list){
                    if(vo.getJdFlag() != 1){
                        newList.add(vo);
                    }
                }
                return newList;
            }
            log.info("22222------------------------------------------"+o.toString());
            return list;
        }
        //重新查询类目树
        List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree(shopId);
        log.info("categoryTree---------------"+categoryTree.toString());
        if (!isNull(categoryTree)) {
            //重新放入redis
            Object treeObject = JSONObject.toJSON(categoryTree);
            redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
            return categoryTree;
        }
        return null;
    }

    @Override
    public List<CommodityCategoryTreeVO> queryNewCategoryTree() {
        //从redis中获取类目树
        Object o = redisUtil.get(CATEGORY_REDIS_KEY);
        List<CommodityCategoryTreeVO> list = JSONObject.parseArray(JSONObject.toJSONString(o), CommodityCategoryTreeVO.class);
        if (!isNull(list)) {
            return list;
        }
        //重新查询类目树
        List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
        if (!isNull(categoryTree)) {
            //重新放入redis
            Object treeObject = JSONObject.toJSON(categoryTree);
            redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
            return categoryTree;
        }
        return null;
    }

    @Override
    public String getCommissionRate(Long id) {
        CommodityCategoryDTO dto = this.selectById(id);
        if (null == dto) {
            return "0.00";
        }
        BigDecimal scale = dto.getDividendScale();
        NumberFormat nbf = NumberFormat.getInstance();
        nbf.setMinimumFractionDigits(3);
        return nbf.format(scale);
    }

//    @Override
//    public List<BrandInfoDTO> queryBrandByCategoryId(Long categoryId) {
//        log.info("queryBrandByCategoryId的类目id : {}", categoryId);
//        List<BrandInfoDTO> tureList = new ArrayList<>();
//        if (null == categoryId) {
//            log.info("queryBrandByCategoryId的类目id为空 : {}", categoryId);
//            // 查询所有品牌
//            Wrapper<BrandInfoDTO> wrapper = new EntityWrapper<>();
//            wrapper.eq("status", 0).eq("is_publish", 1);
//            List<BrandInfoDTO> brandInfoDTOS = brandInfoService.selectList(wrapper);
//            if (isNull(brandInfoDTOS)) {
//                return null;
//            }
//            for (BrandInfoDTO brandInfoDTO : brandInfoDTOS) {
//                Wrapper<CommodityInfoDTO> wrapper2 = new EntityWrapper<>();
//                wrapper2.eq("brand_id", brandInfoDTO.getId());
//                wrapper2.eq("audit_status", 1);
//                wrapper2.eq("is_publish", 1);
//                wrapper2.eq("status", 0);
//                List<CommodityInfoDTO> goodsList = commodityInfoService.selectList(wrapper2);
//                if (isNull(goodsList)) {
//                    continue;
//                }
//                tureList.add(brandInfoDTO);
//            }
//            return tureList;
//        }
//        List<CategoryBrandAttributesVO> list = categoryBrandAttributesRelationService.queryByCategoryId(categoryId);
//        if (!isNull(list)) {
//            for (CategoryBrandAttributesVO vo : list) {
//                Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
//                wrapper.eq("brand_id", vo.getId());
//                wrapper.eq("audit_status", 1);
//                wrapper.eq("is_publish", 1);
//                wrapper.eq("status", 0);
//                wrapper.eq("category_id", categoryId);
//                List<CommodityInfoDTO> goodsList = commodityInfoService.selectList(wrapper);
//                if (isNull(goodsList)) {
//                    continue;
//                }
//                BrandInfoDTO dto = new BrandInfoDTO();
//                dto.setId(vo.getId());
//                dto.setName(vo.getAttributesName());
//                tureList.add(dto);
//            }
//            return tureList;
//        }
//        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("parent_id", categoryId);
//        List<CommodityCategoryDTO> selectList = this.selectList(wrapper);
//        if (isNull(selectList)) {
//            return null;
//        }
//        List<CommodityCategoryDTO> list2 = new ArrayList<>();
//        List<CommodityCategoryDTO> finalCategory = this.getAllFinalCategory(selectList, list2);
//        if (isNull(finalCategory)) {
//            return null;
//        }
//        HashSet<Long> set = new HashSet<>();
//        for (CommodityCategoryDTO dto : finalCategory) {
//            List<CategoryBrandAttributesVO> list3 = categoryBrandAttributesRelationService.queryByCategoryId(dto.getId());
//            if (isNull(list3)) {
//                continue;
//            }
//            for (CategoryBrandAttributesVO attributesVO : list3) {
//                boolean add = set.add(attributesVO.getId());
//                if (!add) {
//                    continue;
//                }
//                Wrapper<CommodityInfoDTO> wrapper2 = new EntityWrapper<>();
//                wrapper2.eq("brand_id", attributesVO.getId());
//                wrapper2.eq("audit_status", 1);
//                wrapper2.eq("is_publish", 1);
//                wrapper2.eq("status", 0);
//                wrapper2.eq("category_id", dto.getId());
//                List<CommodityInfoDTO> goodsList = commodityInfoService.selectList(wrapper2);
//                if (isNull(goodsList)) {
//                    continue;
//                }
//                BrandInfoDTO dto2 = new BrandInfoDTO();
//                dto2.setId(attributesVO.getId());
//                dto2.setName(attributesVO.getAttributesName());
//                tureList.add(dto2);
//            }
//        }
//        return tureList;
//    }

//    @Override
//    public CategoryAdminDetailsNewVO importAttributes(byte[] input, Long id) {
//        // 先查询类目
//        CategoryAdminDetailsNewVO details = this.queryCategoryDetails(id);
//        if (null == details) {
//            return null;
//        }
//        CategoryAdminDetailsNewVO newVO = new CategoryAdminDetailsNewVO();
//        newVO.setId(details.getId());
//        newVO.setCategoryName(details.getCategoryName());
//        newVO.setSort(details.getSort());
//        newVO.setIsDisplayNavBar(details.getIsDisplayNavBar());
//        newVO.setParentId(details.getParentId());
//        if (!isNull(details.getFilterList())) {
//            newVO.setFilterList(details.getFilterList());
//        }
//        // 解析excel
//        // 将文件byte转成inputStream
//        ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
//        try {
//            Workbook workbook = WorkbookFactory.create(inputStream);
//            inputStream.close();
//            // 获取工作表对象
//            Sheet sheet = workbook.getSheetAt(0);
//            // 获取Excel表格中数据的行数
//            int totalRow = sheet.getPhysicalNumberOfRows();
//            // 获取Excel表格中数据的列数
//            int totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
//            // 第一行
//            Row oneRow = sheet.getRow(0);
//            // 所有数据
//            List<CategoryBrandVO> brandList = new ArrayList<>();
//            List<String> name = new ArrayList<>();
//            // 相同品牌的数据过滤
//            List<CategoryBrandVO> brandNames = new ArrayList<>();
//            for (int i = 1; i <= totalRow; i++) {
//                // 行
//                Row row = sheet.getRow(i);
//                // 若有空行继续下一行（因为EXCEL有空行时报错故加上此代码）
//                if (null == row || "".equals(row)) {
//                    totalRow--;
//                    continue;
//                }
//                String check = this.getCellValue(row.getCell(0));
//                if (!StringUtils.isNotBlank(check)) {
//                    totalRow--;
//                    continue;
//                }
//                CategoryBrandVO brandVO = new CategoryBrandVO();
//                CategoryBrandVO names = new CategoryBrandVO();
//                List<CategoryBrandAttributesVO> salesAttributes = new ArrayList<>();
//                List<CategoryBrandAttributesVO> unitAttributes = new ArrayList<>();
//                List<CategoryBrandAttributesVO> parameterAttributes = new ArrayList<>();
//                List<CategoryBrandAttributesVO> labels = new ArrayList<>();
//                String brandName = this.getCellValue(row.getCell(4));
//                for (int j = 4; j <= totalCells; j++) {
//                    String value = this.getCellValue(row.getCell(j));
//                    if (StringUtils.isBlank(value)) {
//                        continue;
//                    }
//                    // 获取标题
//                    String title = this.getCellValue(oneRow.getCell(j));
//                    if (title.contains("销售属性")) {
//                        CategoryBrandAttributesVO bean = new CategoryBrandAttributesVO();
//                        String[] split = value.split("！");
//                        bean.setAttributesName(split[0]);
//                        bean.setNotes(split[1]);
//                        salesAttributes.add(bean);
//                    }
//                    if (title.contains("参数属性")) {
//                        CategoryBrandAttributesVO bean = new CategoryBrandAttributesVO();
//                        String[] split = value.split("！");
//                        bean.setAttributesName(split[0]);
//                        bean.setNotes(split[1]);
//                        parameterAttributes.add(bean);
//                    }
//                    if (title.contains("销售单位")) {
//                        CategoryBrandAttributesVO testBean = new CategoryBrandAttributesVO();
//                        testBean.setAttributesName(value);
//                        unitAttributes.add(testBean);
//                    }
//                    if (title.contains("标签属性")) {
//                        CategoryBrandAttributesVO testBean = new CategoryBrandAttributesVO();
//                        testBean.setAttributesName(value);
//                        labels.add(testBean);
//                    }
//                }
//                brandVO.setBrandName(brandName);
//                brandVO.setUnitIds(unitAttributes);
//                brandVO.setSpecificationIds(salesAttributes);
//                brandVO.setParamIds(parameterAttributes);
//                brandVO.setLabelList(labels);
//                brandList.add(brandVO);
//                boolean contains = name.contains(brandName);
//                if (!contains) {
//                    names.setBrandName(brandName);
//                    names.setUnitIds(new ArrayList<>());
//                    names.setParamIds(new ArrayList<>());
//                    names.setSpecificationIds(new ArrayList<>());
//                    names.setLabelList(new ArrayList<>());
//                    brandNames.add(names);
//                    name.add(brandName);
//                }
//            }
//            List<CategoryBrandVO> importDate = this.getImportDate(brandNames, brandList, newVO);
//            newVO.setBrandList(importDate);
//            return newVO;
//        } catch (Exception e) {
//            log.info("属性导入错误信息:{}", e.getMessage());
//            e.printStackTrace();
//        }
//        return null;
//    }

    @Override
    public List<CommodityCategoryDTO> queryAllFirstLevelCategories() {
        // 先查询零级类目
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", 0);
        List<CommodityCategoryDTO> allZeroLevelCategories = this.selectList(wrapper);
        if (isNull(allZeroLevelCategories)) {
            return null;
        }
        List<Long> ids = new ArrayList<>();
        for (CommodityCategoryDTO zeroLevelCategory : allZeroLevelCategories) {
            ids.add(zeroLevelCategory.getId());
        }
        // 查询所有一级类目
        Wrapper<CommodityCategoryDTO> dtoWrapper = new EntityWrapper<>();
        dtoWrapper.in("parent_id", ids);
        List<CommodityCategoryDTO> allFirstLevelCategories = this.selectList(dtoWrapper);
        if (isNull(allFirstLevelCategories)) {
            return null;
        }
        return allFirstLevelCategories;
    }

    @Override
    public List<CategoryExportVO> getCategoryExportDate() {
        // 查询类目基础数据
        List<CategoryExportQueryVO> list = baseMapper.queryCategoryExportList();
        if (CustomizeUtil.listIsNull(list)) {
            return null;
        }
        try {
            List<CategoryExportVO> result = new ArrayList<>();
            for (CategoryExportQueryVO exportQueryVO : list) {
                CategoryExportVO exportVO = new CategoryExportVO();
                exportVO.setSerialNumber(exportQueryVO.getSerialNumber());
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getZeroLevelName())) {
                    exportVO.setZeroLevelName(exportQueryVO.getZeroLevelName());
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getOneLevelName())) {
                    exportVO.setOneLevelName(exportQueryVO.getOneLevelName());
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getTwoLevelName())) {
                    exportVO.setTwoLevelName(exportQueryVO.getTwoLevelName());
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getThreeLevelName())) {
                    exportVO.setThreeLevelName(exportQueryVO.getThreeLevelName());
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getBrandName())) {
                    exportVO.setBrandName(exportQueryVO.getBrandName());
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getUnitAttribute())) {
                    log.info("导出时的单位ids:{}", exportQueryVO.getUnitAttribute());
                    String attribute = this.handleExportAttribute(exportQueryVO.getUnitAttribute(), 1);
                    exportVO.setUnitAttribute(attribute);
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getSalesAttribute())) {
                    String attribute = this.handleExportAttribute(exportQueryVO.getSalesAttribute(), 3);
                    exportVO.setSalesAttribute(attribute);
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getParameterAttribute())) {
                    String attribute = this.handleExportAttribute(exportQueryVO.getParameterAttribute(), 4);
                    exportVO.setParameterAttribute(attribute);
                }
                if (CustomizeUtil.strIsNotNull(exportQueryVO.getLabelAttribute())) {
                    String attribute = this.handleExportAttribute(exportQueryVO.getLabelAttribute(), 2);
                    exportVO.setLabelAttribute(attribute);
                }
                result.add(exportVO);
            }
            return result;
        } catch (Exception e) {
            log.info("导出全部类目报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return : java.lang.String
     * @Author :chenyu.wang
     * @Description : 处理全部类目导出的属性数据
     * @Date : 10:52 2021.01.15
     * @Param : [attribute, type]
     **/
    private String handleExportAttribute(String attributeId, Integer type) {
        List<String> names = new ArrayList<>();
        if (type == 1) {
            // 单位
            String[] split = attributeId.split(",");
            for (String id : split) {
                CommodityUnitDTO unitDTO = commodityUnitService.selectById(id);
                if (unitDTO != null) {
                    names.add(unitDTO.getName());
                }
            }
        } else if (type == 2) {
            // 标签
            String[] split = attributeId.split(",");
            for (String id : split) {
                CommodityLabelDTO labelDTO = commodityLabelService.selectById(id);
                if (labelDTO != null) {
                    names.add(labelDTO.getName());
                }
            }
        } else if (type == 3) {
            // 销售属性
            String[] split = attributeId.split(",");
            for (String id : split) {
                List<String> attrList = new ArrayList<>();
                CommoditySpecificationDTO specificationDTO = commoditySpecificationService.selectById(id);
                if (specificationDTO != null) {
                    String name = "";
                    // 查询值
                    Wrapper<CommoditySpecificationAttrDTO> wrapper = new EntityWrapper<>();
                    wrapper.eq("specification_id", specificationDTO.getId());
                    List<CommoditySpecificationAttrDTO> dtoList = commoditySpecificationAttrService.selectList(wrapper);
                    if (CustomizeUtil.listIsNotNull(dtoList)) {
                        for (CommoditySpecificationAttrDTO specificationAttrDTO : dtoList) {
                            attrList.add(specificationAttrDTO.getAttrName());
                        }
                        name = Joiner.on(",").join(attrList);
                    }
                    names.add(specificationDTO.getName() + ":" + name);
                }
            }
        } else {
            // 参数属性
            String[] split = attributeId.split(",");
            for (String id : split) {
                List<String> attrList = new ArrayList<>();
                CommodityParamDTO paramDTO = commodityParamService.selectById(id);
                if (paramDTO != null) {
                    String name = "";
                    // 查询值
                    Wrapper<CommodityParamValueDTO> wrapper = new EntityWrapper<>();
                    wrapper.eq("param_id", paramDTO.getId());
                    List<CommodityParamValueDTO> dtoList = commodityParamValueService.selectList(wrapper);
                    if (CustomizeUtil.listIsNotNull(dtoList)) {
                        for (CommodityParamValueDTO specificationAttrDTO : dtoList) {
                            attrList.add(specificationAttrDTO.getValueName());
                        }
                        name = Joiner.on(",").join(attrList);
                    }
                    names.add(paramDTO.getParamName() + ":" + name);
                }
            }
        }
        String join = "";
        if (CustomizeUtil.listIsNotNull(names)) {
            join = Joiner.on(";").join(names);
        }
        log.info("类目导出属性拼接:{}", join);
        return join;
    }

//    /**
//     * @Description: 处理导入的数据
//     * @Author: chenyu.wang
//     * @Params: [brandNames, brandList]
//     * @Date: 2020.11.30 15:58
//     */
//    private List<CategoryBrandVO> getImportDate(List<CategoryBrandVO> brandNames, List<CategoryBrandVO> brandList, CategoryAdminDetailsNewVO category) {
//        for (CategoryBrandVO brandName : brandNames) {
//            CategoryBrandVO brandVO = this.checkBrand(brandName.getBrandName());
//            brandName.setBrandName(brandVO.getBrandName());
//            brandName.setBrandId(brandVO.getBrandId());
//            brandName.setNotes(brandVO.getNotes());
//            log.info("去重后的品牌:{}", brandName.getBrandName());
//            List<String> unitName = new ArrayList<>();
//            List<Long> params = new ArrayList<>();
//            List<Long> seal = new ArrayList<>();
//            HashSet<Long> set = new HashSet<>();
//            for (CategoryBrandVO vo : brandList) {
//                if (vo.getBrandName().equals(brandName.getBrandName())) {
//                    log.info("处理品牌属性");
//                    // 处理单位
//                    for (CategoryBrandAttributesVO voUnitId : vo.getUnitIds()) {
//                        if (!unitName.contains(voUnitId.getAttributesName())) {
//                            unitName.add(voUnitId.getAttributesName());
//                            CategoryBrandAttributesVO unit = this.checkUnit(voUnitId.getAttributesName());
//                            brandName.getUnitIds().add(unit);
//                        }
//                    }
//                    // 处理参数属性
//                    List<CategoryBrandAttributesVO> list = this.checkParameterAttributes(vo.getParamIds(), category, brandName);
//                    for (CategoryBrandAttributesVO categoryBrandAttributesVO : list) {
//                        if (!params.contains(categoryBrandAttributesVO.getId())) {
//                            params.add(categoryBrandAttributesVO.getId());
//                            brandName.getParamIds().add(categoryBrandAttributesVO);
//                        }
//                    }
//                    // 处理规格属性
//                    List<CategoryBrandAttributesVO> specificationAttributes = this.checkSpecificationAttributes(vo.getSpecificationIds(), category, brandName);
//                    for (CategoryBrandAttributesVO specificationAttribute : specificationAttributes) {
//                        if (!seal.contains(specificationAttribute.getId())) {
//                            seal.add(specificationAttribute.getId());
//                            brandName.getSpecificationIds().add(specificationAttribute);
//                        }
//                    }
//                    // 处理标签
//                    if (!isNull(vo.getLabelList())) {
//                        for (CategoryBrandAttributesVO categoryBrandAttributesVO : vo.getLabelList()) {
//                            CategoryBrandAttributesVO checkLabel = this.checkLabel(categoryBrandAttributesVO.getAttributesName());
//                            boolean add = set.add(checkLabel.getId());
//                            if (!add) {
//                                continue;
//                            }
//                            brandName.getLabelList().add(checkLabel);
//                        }
//                    }
//                }
//            }
//        }
//        return brandNames;
//    }

    /**
     * @Description: 导入检查标签属性是否存在
     * @Author: chenyu.wang
     * @Params: [name]
     * @Date: 2020.12.30 11:52
     */
    public CategoryBrandAttributesVO checkLabel(String name) {
        CategoryBrandAttributesVO attributesVO = new CategoryBrandAttributesVO();
        Wrapper<CommodityLabelDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("name", name);
        CommodityLabelDTO selectOne = commodityLabelService.selectOne(wrapper);
        if (selectOne == null) {
            Long id = ymlConfig.getPkId();
            CommodityLabelDTO dto = new CommodityLabelDTO();
            dto.setId(id);
            dto.setName(name);
            commodityLabelService.insert(dto);
            attributesVO.setId(id);
            attributesVO.setAttributesName(name);
        } else {
            attributesVO.setId(selectOne.getId());
            attributesVO.setAttributesName(selectOne.getName());
        }
        return attributesVO;
    }

    /**
     * @Description: 导入时判断参数是否存在品牌，有则返回，没有则新建
     * @Author: chenyu.wang
     * @Params: [list]
     * @Date: 2020.11.30 15:58
     */
    public List<CategoryBrandAttributesVO> checkParameterAttributes(List<CategoryBrandAttributesVO> list, CategoryAdminDetailsNewVO category, CategoryBrandVO brand) {
        List<CategoryBrandAttributesVO> result = new ArrayList<>();
        String note = category.getCategoryName() + " " + brand.getBrandName();
        for (CategoryBrandAttributesVO attributesVO : list) {
            String name = attributesVO.getAttributesName();
            String valueName = attributesVO.getNotes();
            // 先查询是否存在该名称的参数,不存在就添加，存在就返回
            Wrapper<CommodityParamDTO> dtoWrapper = new EntityWrapper<>();
            dtoWrapper.eq("param_name", name).eq("notes", note);
            CommodityParamDTO commodityParamDTO = commodityParamService.selectOne(dtoWrapper);
            if (null == commodityParamDTO) {
                CategoryBrandAttributesVO vo = this.addParam(name, note, valueName);
                result.add(vo);
                continue;
            }
            Wrapper<CommodityParamValueDTO> valueDTOWrapper = new EntityWrapper<>();
            valueDTOWrapper.eq("param_id", commodityParamDTO.getId()).eq("value_name", valueName);
            CommodityParamValueDTO valueDTO = commodityParamValueService.selectOne(valueDTOWrapper);
            if (null == valueDTO) {
                CommodityParamValueDTO paramValueDTO = new CommodityParamValueDTO();
                paramValueDTO.setParamId(commodityParamDTO.getId());
                paramValueDTO.setValueName(valueName);
                paramValueDTO.setId(ymlConfig.getPkId());
                commodityParamValueService.insert(paramValueDTO);
            }
            CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
            vo.setId(commodityParamDTO.getId());
            vo.setAttributesName(commodityParamDTO.getParamName());
            vo.setNotes(commodityParamDTO.getNotes());
            result.add(vo);
        }
        return result;
    }

    /**
     * @Description: 导入时判断检查规格属性
     * @Author: chenyu.wang
     * @Params: [list, category, brand]
     * @Date: 2020.12.01 15:21
     */
    public List<CategoryBrandAttributesVO> checkSpecificationAttributes(List<CategoryBrandAttributesVO> list, CategoryAdminDetailsNewVO category, CategoryBrandVO brand) {
        List<CategoryBrandAttributesVO> result = new ArrayList<>();
        String note = category.getCategoryName() + " " + brand.getBrandName();
        for (CategoryBrandAttributesVO attributesVO : list) {
            // 参数名称
            String name = attributesVO.getAttributesName();
            // 参数值
            String valueName = attributesVO.getNotes();
            // 先查询是否存在该名称的参数,不存在就添加，存在就返回
            Wrapper<CommoditySpecificationDTO> dtoWrapper = new EntityWrapper<>();
            dtoWrapper.eq("name", name).eq("notes", note);
            CommoditySpecificationDTO commodityParamDTO = commoditySpecificationService.selectOne(dtoWrapper);
            if (null == commodityParamDTO) {
                CategoryBrandAttributesVO vo = this.addSalesAttributes(name, note, valueName);
                result.add(vo);
                continue;
            }
            Wrapper<CommoditySpecificationAttrDTO> valueDTOWrapper = new EntityWrapper<>();
            valueDTOWrapper.eq("specification_id", commodityParamDTO.getId()).eq("attr_name", valueName);
            CommoditySpecificationAttrDTO valueDTO = commoditySpecificationAttrService.selectOne(valueDTOWrapper);
            if (null == valueDTO) {
                CommoditySpecificationAttrDTO paramValueDTO = new CommoditySpecificationAttrDTO();
                paramValueDTO.setSpecificationId(commodityParamDTO.getId());
                paramValueDTO.setAttrName(valueName);
                paramValueDTO.setId(ymlConfig.getPkId());
                commoditySpecificationAttrService.insert(paramValueDTO);
            }
            CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
            vo.setId(commodityParamDTO.getId());
            vo.setAttributesName(commodityParamDTO.getName());
            vo.setNotes(commodityParamDTO.getNotes());
            result.add(vo);
        }
        return result;
    }

    /**
     * @Description: 导入时添加参数信息
     * @Author: chenyu.wang
     * @Params: [name, note, valueName]
     * @Date: 2020.12.01 14:36
     */
    private CategoryBrandAttributesVO addParam(String name, String note, String valueName) {
        Long id = ymlConfig.getPkId();
        CommodityParamDTO insertDto = new CommodityParamDTO();
        insertDto.setParamName(name);
        insertDto.setStatus(0);
        insertDto.setIsPublish(1);
        insertDto.setSort(0);
        insertDto.setNotes(note);
        insertDto.setId(id);
        boolean insert = commodityParamService.insert(insertDto);
        if (!insert) {
            throw new RuntimeException("导入时新增参数失败!");
        }
        CommodityParamValueDTO paramValueDTO = new CommodityParamValueDTO();
        paramValueDTO.setParamId(id);
        paramValueDTO.setValueName(valueName);
        paramValueDTO.setId(ymlConfig.getPkId());
        commodityParamValueService.insert(paramValueDTO);
        CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
        vo.setId(id);
        vo.setAttributesName(name);
        vo.setNotes(note);
        return vo;
    }

    /**
     * @Description: 导入时新增规格属性
     * @Author: chenyu.wang
     * @Params: [name, note, valueName]
     * @Date: 2020.12.01 14:44
     */
    private CategoryBrandAttributesVO addSalesAttributes(String name, String note, String valueName) {
        Long id = ymlConfig.getPkId();
        CommoditySpecificationDTO insertDto = new CommoditySpecificationDTO();
        insertDto.setName(name);
        insertDto.setSort(0);
        insertDto.setStatus(0);
        insertDto.setIsPublish(1);
        insertDto.setNotes(note);
        insertDto.setId(id);
        boolean insert = commoditySpecificationService.insert(insertDto);
        if (!insert) {
            log.info("导入时添加规格属性失败");
            throw new RuntimeException("导入时添加规格属性失败!");
        }
        CommoditySpecificationAttrDTO specificationAttrDTO = new CommoditySpecificationAttrDTO();
        specificationAttrDTO.setSpecificationId(id);
        specificationAttrDTO.setAttrName(valueName);
        specificationAttrDTO.setStatus(0);
        specificationAttrDTO.setIsPublish(1);
        specificationAttrDTO.setId(ymlConfig.getPkId());
        commoditySpecificationAttrService.insert(specificationAttrDTO);
        CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
        vo.setId(id);
        vo.setAttributesName(name);
        vo.setNotes(note);
        return vo;
    }

    /**
     * @Description: 获取excel数据时对数据类型的判定及处理
     * @Author: chenyu.wang
     * @Params: [cell]
     * @Date: 2020.11.24 11:20
     */
    private String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue().trim();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                DecimalFormat df = new DecimalFormat("0");

                cellValue = df.format(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
        }
        return cellValue;
    }

//    /**
//     * @Description: 导入时根据品牌名称判断是否存在品牌，有则返回，没有则新建
//     * @Author: chenyu.wang
//     * @Params: [brandName]
//     * @Date: 2020.11.24 17:07
//     */
//    @Override
//    public CategoryBrandVO checkBrand(String brandName) {
//        Wrapper<BrandInfoDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("name", brandName);
//        BrandInfoDTO dto = brandInfoService.selectOne(wrapper);
//        if (null != dto) {
//            CategoryBrandVO vo = new CategoryBrandVO();
//            vo.setBrandId(dto.getId());
//            vo.setBrandName(dto.getName());
//            vo.setNotes(dto.getNotes());
//            return vo;
//        }
//        Long id = ymlConfig.getPkId();
//        BrandInfoDTO insertDto = new BrandInfoDTO();
//        insertDto.setName(brandName);
//        insertDto.setInitials(PinYinUtils.getPinYinHeadCharFirstBrand(brandName));
//        insertDto.setStatus(0);
//        insertDto.setIsPublish(1);
//        insertDto.setNotes("导入属性时新增的品牌");
//        insertDto.setId(id);
//        boolean insert = brandInfoService.insert(insertDto);
//        if (!insert) {
//            throw new RuntimeException("导入新增品牌失败!");
//        }
//        CategoryBrandVO vo = new CategoryBrandVO();
//        vo.setBrandId(id);
//        vo.setBrandName(brandName);
//        return vo;
//    }

    /**
     * @Description: 导入属性时判断单位是否存在，不存在就创建新的
     * @Author: chenyu.wang
     * @Params: [unitName]
     * @Date: 2020.11.24 17:23
     */
    public CategoryBrandAttributesVO checkUnit(String unitName) {
        Wrapper<CommodityUnitDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("name", unitName);
        CommodityUnitDTO dto = commodityUnitService.selectOne(wrapper);
        if (null != dto) {
            CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
            vo.setId(dto.getId());
            vo.setAttributesName(dto.getName());
            vo.setNotes(dto.getNotes());
            return vo;
        }
        Long id = ymlConfig.getPkId();
        CommodityUnitDTO insertDto = new CommodityUnitDTO();
        insertDto.setName(unitName);
        insertDto.setStatus(0);
        insertDto.setIsPublish(1);
        insertDto.setNotes("导入属性时新增的单位");
        insertDto.setId(id);
        boolean insert = commodityUnitService.insert(insertDto);
        if (!insert) {
            throw new RuntimeException("导入新增单位失败!");
        }
        CategoryBrandAttributesVO vo = new CategoryBrandAttributesVO();
        vo.setId(id);
        vo.setAttributesName(unitName);
        return vo;
    }

    /**
     * @Description: 10分钟定时任务修改佣金比例
     * @Author: liyang
     * @param dtos
     * @return
     */
    @Override
    public boolean updateDividendScaleByScheduled(List<CommodityCategoryDTO> dtos) {
        boolean flag = this.updateBatchById (dtos);
        String ids = "";
        for (CommodityCategoryDTO dto: dtos) {
            ids +=dto.getId () + ",";
        }
        if (ids.length() > 0){
            ids = ids.substring (0,ids.length()-1);
        }
        boolean flag2 = shopCategoryRelationService.updateShopDividendScaleByScheduled (ids);
        if (flag&&flag2){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<CommodityCategoryTreeVO> getByChildId(Long id, List<CommodityCategoryTreeVO> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        CommodityCategoryDTO dto = this.selectById(id);
        if (dto == null) {
            return null;
        }
        if (dto.getParentId() == 0) {
            return list;
        } else {
            CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
            treeVO.setId(dto.getId());
            treeVO.setName(dto.getName());
            treeVO.setInitials(dto.getInitials());
            treeVO.setParentId(dto.getParentId());
            treeVO.setSort(dto.getSort());
            treeVO.setCode(dto.getCode());
            list.add(treeVO);
        }
        return this.getByChildId(dto.getParentId(), list);
    }

    @Override
    public List<CommodityCategoryTreeVO> queryShopCategory(Long shopId) {
        //查询店铺下类目(终极)
        List<CommodityShopCategoryVO> shopCategory = baseMapper.queryShopCategory(shopId);
        if (shopCategory != null && shopCategory.size() > 0) {
            List<CommodityCategoryTreeVO> root = new ArrayList<>();
            for (CommodityShopCategoryVO shopCategoryVO : shopCategory) {
                List<CommodityCategoryTreeVO> list = this.getByChildId(shopCategoryVO.getId(), new ArrayList<>());
                root.addAll(list);
            }
            //查询最顶级的类目
            Wrapper<CommodityCategoryDTO> wrapperParent = new EntityWrapper<>();
            wrapperParent.eq("is_publish", 1).eq("status", 0)
                    .eq("parent_id", 0).orderBy("sort", true);
            List<CommodityCategoryDTO> parentList = this.selectList(wrapperParent);
            for (CommodityCategoryDTO commodityCategoryDTO : parentList) {
                CommodityCategoryTreeVO commodityCategoryTreeVO = new CommodityCategoryTreeVO();
                BeanUtils.copyProperties(commodityCategoryDTO, commodityCategoryTreeVO);
                root.add(commodityCategoryTreeVO);
            }
            //去重
            List<CommodityCategoryTreeVO> realRoot = root.stream().distinct().collect(Collectors.toList());
            //构建树形结构
            List<CommodityCategoryTreeVO> list = this.builTree(realRoot);
            List<CommodityCategoryTreeVO> real = new ArrayList<>();
            for (CommodityCategoryTreeVO categoryTreeVO : list) {
                real.addAll(categoryTreeVO.getChildList());
            }
            return real.stream().distinct().collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<CommodityShopCategoryVO> queryShopCategory(Long shopId,String cid) {
        //查询店铺下类目(终极)
        List<CommodityShopCategoryVO> shopCategory = baseMapper.queryShopCategoryByCid(shopId,cid);
        return shopCategory;
    }

    //建立树形结构
    public List<CommodityCategoryTreeVO> builTree(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> treeMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : getRootNode(menuList)) {
            menuNode = this.buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private CommodityCategoryTreeVO buildChilTree(CommodityCategoryTreeVO pNode, List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> chilMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(this.buildChilTree(menuNode, menuList));
            }
        }
        pNode.setChildList(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<CommodityCategoryTreeVO> getRootNode(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> rootMenuLists = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().intValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

    @Override
    public List<CommodityShopAvailableAreaVO> queryShopAvailableArea(Long shopId) {
        return baseMapper.queryShopAvailableArea(shopId);
    }

    @Override
    public Result<List<String>> removeById(Long id) {
        this.deleteById(id);
        return null;
    }

    @Transactional
    @Override
    public Result<List<String>> updateCategory(CommodityCategorySaveBO bo) {
        Result<List<String>> result = new Result<>();
        CommodityCategoryDTO byId = this.selectById(bo.getId());
        if (byId == null) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340000.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340000.getMsg());
            return result;
        }
        CommodityCategoryDTO updateDto = new CommodityCategoryDTO();
        updateDto.setName(bo.getCategoryName());//类目名称
        updateDto.setInitials(PinYinUtils.getPinYinHeadCharFirstBrand(bo.getCategoryName()));//首字母缩写
        updateDto.setParentId(bo.getParentId());//父级id
        updateDto.setSort(bo.getSort());//排序
        updateDto.setIsPublish(bo.getIsDisplayNavBar());//是否显示
        updateDto.setId(byId.getId());//id
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.FAIL_100008.getCode());
            result.setMsg(CodeEnum.FAIL_100008.getMsg());
            return result;
        }
        //只有顶级才能有筛选属性
        if (bo.getParentId() == ZERO) {
            if (StringUtils.isNotBlank(bo.getFilterIds())) {
                commodityCategoryFilterRelationService.deleteByCategoryId(bo.getId());
                commodityCategoryFilterRelationService.add(bo.getId(), bo.getFilterIds());
            }
        } else {
            //参数属性、销售属性、单位
            if (StringUtils.isNotBlank(bo.getBrandList())) {
                List<CategoryBrandAttributesRelationDTO> list = JSONObject.parseArray(bo.getBrandList(), CategoryBrandAttributesRelationDTO.class);
                List<CategoryBrandAttributesRelationDTO> addList = new ArrayList<>();
                for (CategoryBrandAttributesRelationDTO dto : list) {
                    //先删除
                    categoryBrandAttributesRelationService.deleteByTwoId(byId.getId(), dto.getBrandId());
                    log.info("类目添加属性参数 : {}", dto);
                    CategoryBrandAttributesRelationDTO addDto = new CategoryBrandAttributesRelationDTO();
                    addDto.setId(ymlConfig.getPkId());
                    addDto.setCategoryId(byId.getId());
                    addDto.setBrandId(dto.getBrandId());
                    if (StringUtils.isNotBlank(dto.getSpecificationIds())) {
                        addDto.setSpecificationIds(dto.getSpecificationIds());
                    }
                    if (StringUtils.isNotBlank(dto.getParamIds())) {
                        addDto.setParamIds(dto.getParamIds());
                    }
                    if (StringUtils.isNotBlank(dto.getUnitIds())) {
                        addDto.setUnitIds(dto.getUnitIds());
                    }
                    addList.add(addDto);
                }
                categoryBrandAttributesRelationService.insertBatch(addList);
            }
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    @Override
    public List<CommodityFilterAttributesNewVO> getFilterAttributes(Long categoryId, String filterName) {
        return commodityFilterAttributesService.queryByCategoryId(categoryId, filterName);
    }

    @Override
    public List<CommodityCategoryTreeVO> queryShopCategoryByBrandId(Long brandId, Long shopId) {
        //查询店铺下类目(终极)
        List<CommodityShopCategoryVO> shopCategory = baseMapper.queryShopCategoryByBrandId(brandId, shopId);
        if (shopCategory != null && shopCategory.size() > 0) {
            List<CommodityCategoryTreeVO> root = new ArrayList<>();
            for (CommodityShopCategoryVO shopCategoryVO : shopCategory) {
                List<CommodityCategoryTreeVO> list = this.getByChildId(shopCategoryVO.getId(), new ArrayList<>());
                root.addAll(list);
            }
            //查询最顶级的类目
            Wrapper<CommodityCategoryDTO> wrapperParent = new EntityWrapper<>();
            wrapperParent.eq("is_publish", 1).eq("status", 0)
                    .eq("parent_id", 0).orderBy("sort", true);
            List<CommodityCategoryDTO> parentList = this.selectList(wrapperParent);
            for (CommodityCategoryDTO commodityCategoryDTO : parentList) {
                CommodityCategoryTreeVO commodityCategoryTreeVO = new CommodityCategoryTreeVO();
                BeanUtils.copyProperties(commodityCategoryDTO, commodityCategoryTreeVO);
                root.add(commodityCategoryTreeVO);
            }
            //去重
            List<CommodityCategoryTreeVO> realRoot = root.stream().distinct().collect(Collectors.toList());
            //构建树形结构
            List<CommodityCategoryTreeVO> list = this.builTree(realRoot);
            List<CommodityCategoryTreeVO> real = new ArrayList<>();
            for (CommodityCategoryTreeVO categoryTreeVO : list) {
                real.addAll(categoryTreeVO.getChildList());
            }
            return real.stream().distinct().collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<CommodityCategoryTreeVO> getTreeByIds(Long id) {
        //查询零级下所有一级
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", 0);
        wrapper.eq("is_publish", 1);
        wrapper.eq("parent_id", id);
        wrapper.orderBy("sort", true);
        List<CommodityCategoryDTO> list = this.selectList(wrapper);
        //零级
        CommodityCategoryDTO commodityCategoryDTOS = selectById(id);
        List<CommodityCategoryTreeVO> commodityCategoryTreeVOList = new ArrayList<>();
        for (CommodityCategoryDTO categoryDTO : list) {
            CommodityCategoryTreeVO tempCommodityCategoryTreeVO = new CommodityCategoryTreeVO();
            BeanUtils.copyProperties(categoryDTO, tempCommodityCategoryTreeVO);
            commodityCategoryTreeVOList.add(tempCommodityCategoryTreeVO);
        }
        List<CommodityCategoryTreeVO> commodityCategoryTreeVOS = builCategoryTreeBySelectCategoryId(commodityCategoryTreeVOList, list);
        CommodityCategoryTreeVO tempCommodityCategoryTreeVO = new CommodityCategoryTreeVO();
        BeanUtils.copyProperties(commodityCategoryDTOS, tempCommodityCategoryTreeVO);
        commodityCategoryTreeVOS.add(tempCommodityCategoryTreeVO);
        List<CommodityCategoryTreeVO> commodityCategoryTreeVOS1 = builTree(commodityCategoryTreeVOS);
        List<CommodityCategoryTreeVO> real = new ArrayList<>();
        for (CommodityCategoryTreeVO treeVO : commodityCategoryTreeVOS1) {
            real.addAll(treeVO.getChildList());
        }
        return real;
    }

    /*
     * @description:判断一个类目是否处于最低级，如果为空，则是最低级，反则不是
     * @author: chenyu.wang
     * @date: 2020-09-09
     */
    @Override
    public Integer getCheckCategory(Long id) {
        //0是最低级,1不是最低级
        int result;
        CommodityCategoryDTO dto = baseMapper.getCheckCategory(id);
        if (dto == null) {
            result = ZERO;
        } else {
            result = ONE;
        }
        return result;
    }

    /*
     * @description:根据低级类目id封装顶级
     * @author: chenyu.wang
     * @date: 2020-09-09
     * @return:
     */
    @Override
    public String creatTreeById(Long categoryId, String names) {
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO);
        wrapper.eq("id", categoryId);
        CommodityCategoryDTO dto = this.selectOne(wrapper);
        if (dto != null) {
            if (dto.getParentId() == ZERO) {
                StringBuilder stringBuffer = new StringBuilder(names);
                stringBuffer.insert(ZERO, dto.getName() + ">");
                return stringBuffer.toString();
            } else {
                StringBuilder stringBuffer = new StringBuilder(names);
                stringBuffer.insert(ZERO, dto.getName() + ">");
                return this.creatTreeById(dto.getParentId(), stringBuffer.toString());
            }
        }
        return "";
    }

    /*
     * @description:获取类目详情
     * @author: chenyu.wang
     * @date: 2020-09-09
     * @return:
     */
    @Override
    public CategoryAdminDetailsNewVO queryCategoryDetails(Long id) {
        CategoryAdminDetailsNewVO vo = new CategoryAdminDetailsNewVO();
        //根据id查询类目
        CommodityCategoryDTO dto = this.selectById(id);
        if (dto == null) {
            return null;
        }
        vo.setId(dto.getId());//类目Id
        vo.setCategoryName(dto.getName());//类目名称
        vo.setSort(dto.getSort());//排序
        vo.setIsDisplayNavBar(dto.getIsPublish());//是否显示
        vo.setParentId(dto.getParentId());//父级id
        vo.setJdFlag(dto.getJdFlag());
        vo.setJdCode(dto.getJdCode());
        //查询筛选属性
        List<CategoryBrandAttributesVO> filters = baseMapper.queryByCategoryId(dto.getId());
        if (!isNull(filters)) {
            vo.setFilterList(filters);
        }
        //查询类目品牌关系
        List<CategoryBrandVO> brandList = baseMapper.queryBrandByCategoryId(dto.getId());
        if (!isNull(brandList)) {
            for (CategoryBrandVO brandVO : brandList) {
                //查询类目品牌规格属性
                List<CategoryBrandAttributesVO> specificationVOS = baseMapper.queryCategoryBrandSpecification(dto.getId(), brandVO.getBrandId());
                specificationVOS.removeAll(Collections.singleton(null));
                if (!isNull(specificationVOS)) {
                    brandVO.setSpecificationIds(specificationVOS);
                }
                //查询类目品牌参数属性
                List<CategoryBrandAttributesVO> paramList = baseMapper.queryCategoryBrandParam(dto.getId(), brandVO.getBrandId());
                paramList.removeAll(Collections.singleton(null));
                if (!isNull(paramList)) {
                    brandVO.setParamIds(paramList);
                }
                //查询类目品牌单位属性
                List<CategoryBrandAttributesVO> unitList = baseMapper.queryCategoryBrandUnit(dto.getId(), brandVO.getBrandId());
                unitList.removeAll(Collections.singleton(null));
                if (!isNull(unitList)) {
                    brandVO.setUnitIds(unitList);
                }
                // 获取类目关联标签
                List<CategoryBrandAttributesVO> labelCollection = baseMapper.queryCategoryBrandLabel(dto.getId(), brandVO.getBrandId());
                labelCollection.removeAll(Collections.singleton(null));
                if (!isNull(labelCollection)) {
                    brandVO.setLabelList(labelCollection);
                }
            }
            vo.setBrandList(brandList);
        }
        return vo;
    }

    /*
     * @description:后台管理系统修改导航栏是否显示, 0不显示，1显示
     * @author: chenyu.wang
     * @date: 2020-09-11
     * @return:
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateIsPush(Long id, Integer state) {
        CommodityCategoryDTO dto = this.selectById(id);
        if (null == dto) {
            return false;
        }
        CommodityCategoryDTO updateDTO = new CommodityCategoryDTO();
        updateDTO.setId(dto.getId());
        updateDTO.setIsPublish(state);//0不显示，1显示
        boolean update = this.updateById(updateDTO);
        if (!update) {
            return false;
        }
        //查询该类目是否有下级,若没有返回成功,有同样修改
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", dto.getId());
        List<CommodityCategoryDTO> list = this.selectList(wrapper);
        if (isNull(list)) {
            //重新获取类目树放进redis
            List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
            if (!isNull(categoryTree)) {
                //重新放入redis
                Object treeObject = JSONObject.toJSON(categoryTree);
                redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
            }
            return true;
        }
        List<CommodityCategoryDTO> updateList = new ArrayList<>();
        for (CommodityCategoryDTO categoryDTO : list) {
            CommodityCategoryDTO childDTO = new CommodityCategoryDTO();
            childDTO.setId(categoryDTO.getId());
            childDTO.setIsPublish(state);
            updateList.add(childDTO);
        }
        boolean updateBatchById = this.updateBatchById(updateList);
        if (!updateBatchById) {
            throw new RuntimeException("修改失败!");
        }
        //重新获取类目树放进redis
        List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
        if (!isNull(categoryTree)) {
            //重新放入redis
            Object treeObject = JSONObject.toJSON(categoryTree);
            redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
        }
        return true;
    }

    @Override
    public List<CategoryBrandAttributesVO> getSalesAttributes(Long categoryId, Long brandId) {
        return baseMapper.queryCategoryBrandSpecification(categoryId, brandId);
    }

    /*
     * @description:商城询价页根据类目id获取品牌信息
     * @author: chenyu.wang
     * @date: 2020-09-17
     * @return:
     */
    @Override
    public List<CommodityInquiryBrandVO> queryInquiryBrandByCategoryId(Long categoryId) {
        return baseMapper.queryInquiryBrandByCategoryId(categoryId);
    }

    /*
     * @description:新的添加类目方法
     * @author: chenyu.wang
     * @date: 2020-09-17
     * @return:
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<List<String>> addNewCategory(CommodityAdminCategoryAddBO bo) {
        Result<List<String>> result = new Result<>();
        //判断父级是否包含属性，有的话不能作为父级
        if (bo.getParentId() != 0) {
            Wrapper<CategoryBrandAttributesRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("category_id", bo.getParentId());
            List<CategoryBrandAttributesRelationDTO> relationDTOList = categoryBrandAttributesRelationService.selectList(wrapper);
            if (!isNull(relationDTOList)) {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340014.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340014.getMsg());
                return result;
            }
        }
        CommodityCategoryDTO insertDTO = new CommodityCategoryDTO();
        Long id = ymlConfig.getPkId();//类目id
        insertDTO.setId(id);
        insertDTO.setCreateUserId(bo.getUserId());//用户id
        insertDTO.setName(bo.getCategoryName());//类目名称
        insertDTO.setInitials(PinYinUtils.getPinYinHeadCharFirstBrand(bo.getCategoryName()));
        insertDTO.setParentId(bo.getParentId());//父id
        insertDTO.setSort(bo.getSort());//排序号
        insertDTO.setCode(UtilConstants.getlinkNo());//唯一标识
        insertDTO.setIsPublish(bo.getIsDisplayNavBar());//是否显示在导航栏 0不显示，1显示
        insertDTO.setJdFlag(bo.getJdFlag());//是否京东类目
        insertDTO.setJdCode(bo.getJdCode());//京东类目编码
        this.getAddSort(bo.getParentId(), bo.getSort());//修改排序
        boolean insert = this.insert(insertDTO);//保存类目
        if (!insert) {
            result.setCode(CodeEnum.FAIL_100007.getCode());
            result.setMsg(CodeEnum.FAIL_100007.getMsg());
            return result;
        }
        if (bo.getParentId() == 0) {
            if (StringUtils.isNotBlank(bo.getFilterIds())) {
                commodityCategoryFilterRelationService.add(id, bo.getFilterIds());//添加筛选属性
            }
            //重新获取类目树放进redis
            List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
            if (!isNull(categoryTree)) {
                //重新放入redis
                Object treeObject = JSONObject.toJSON(categoryTree);
                redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
            }
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
        //销售属性，参数属性，单位属性
        if (StringUtils.isNotBlank(bo.getBrandList())) {
            List<CategoryBrandAttributesRelationDTO> list = JSONObject.parseArray(bo.getBrandList(), CategoryBrandAttributesRelationDTO.class);
            List<CategoryBrandAttributesRelationDTO> addList = new ArrayList<>();
            for (CategoryBrandAttributesRelationDTO dto : list) {
                log.info("类目添加属性参数 : {}", dto);
                CategoryBrandAttributesRelationDTO addDto = new CategoryBrandAttributesRelationDTO();
                addDto.setId(ymlConfig.getPkId());
                addDto.setCategoryId(id);
                addDto.setBrandId(dto.getBrandId());
                if (StringUtils.isNotBlank(dto.getSpecificationIds())) {
                    String[] split = dto.getSpecificationIds().split(",");
                    Arrays.sort(split);
                    String real = String.join(",", split);//给属性id排序之后再保存
                    addDto.setSpecificationIds(real);
                }
                if (StringUtils.isNotBlank(dto.getParamIds())) {
                    String[] split = dto.getParamIds().split(",");
                    Arrays.sort(split);
                    String real = String.join(",", split);//给属性id排序之后再保存
                    addDto.setParamIds(real);
                }
                if (StringUtils.isNotBlank(dto.getUnitIds())) {
                    String[] split = dto.getUnitIds().split(",");
                    Arrays.sort(split);
                    String real = String.join(",", split);//给属性id排序之后再保存
                    addDto.setUnitIds(real);
                }
                if (StringUtils.isNotBlank(dto.getLabelIds())) {
                    String ids = getIds(dto.getLabelIds());
                    addDto.setLabelIds(ids);
                }
                addList.add(addDto);
            }
            if (!isNull(addList)) {
                categoryBrandAttributesRelationService.insertBatch(addList);
            }
        }
        //重新获取类目树放进redis
        List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
        if (!isNull(categoryTree)) {
            //重新放入redis
            Object treeObject = JSONObject.toJSON(categoryTree);
            redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<List<String>> updateNewCategory(CommodityCategorySaveBO bo) {
        Result<List<String>> result = new Result<>();
        //判断类目是否为空
        CommodityCategoryDTO byId = this.selectById(bo.getId());
        if (byId == null) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340000.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340000.getMsg());
            return result;
        }
        //判断父级是否包含属性，有的话不能作为父级
        if (bo.getParentId() != 0) {
            Wrapper<CategoryBrandAttributesRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("category_id", bo.getParentId());
            List<CategoryBrandAttributesRelationDTO> relationDTOList = categoryBrandAttributesRelationService.selectList(wrapper);
            if (!isNull(relationDTOList)) {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340014.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340014.getMsg());
                return result;
            }
        }
        CommodityCategoryDTO updateDto = new CommodityCategoryDTO();
        updateDto.setName(bo.getCategoryName());//类目名称
        updateDto.setInitials(PinYinUtils.getPinYinHeadCharFirstBrand(bo.getCategoryName()));//首字母缩写
        updateDto.setParentId(bo.getParentId());//父级id
        updateDto.setSort(bo.getSort());//排序
        updateDto.setIsPublish(bo.getIsDisplayNavBar());//是否显示
        updateDto.setId(byId.getId());//id
        updateDto.setJdFlag(bo.getJdFlag());//是否京东类目
        updateDto.setJdCode(bo.getJdCode());//京东编码
        if (byId.getSort() != null && !byId.getSort().equals(bo.getSort())) {
            this.getSort(bo.getParentId(), byId.getSort(), bo.getSort());//排序
        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.FAIL_100008.getCode());
            result.setMsg(CodeEnum.FAIL_100008.getMsg());
            return result;
        }
        //顶级才有筛选属性，修改完成后直接返回
        if (bo.getParentId() == 0) {
            if (StringUtils.isNotBlank(bo.getFilterIds())) {
                //属性关联后不能删除，只能增加，所以只有添加，查询的时候去重
                commodityCategoryFilterRelationService.add(bo.getId(), bo.getFilterIds());
            }
            //重新获取类目树放进redis
            List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
            if (!isNull(categoryTree)) {
                //重新放入redis
                Object treeObject = JSONObject.toJSON(categoryTree);
                redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
            }
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
        //参数属性、销售属性、单位
        if (StringUtils.isNotBlank(bo.getBrandList())) {
            List<CategoryBrandAttributesRelationDTO> list = JSONObject.parseArray(bo.getBrandList(), CategoryBrandAttributesRelationDTO.class);
            for (CategoryBrandAttributesRelationDTO dto : list) {
                Wrapper<CategoryBrandAttributesRelationDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("category_id", byId.getId());
                wrapper.eq("brand_id", dto.getBrandId());
                CategoryBrandAttributesRelationDTO relationDTO = categoryBrandAttributesRelationService.selectOne(wrapper);
                if (relationDTO == null) {
                    //查询如果没有就新增
                    CategoryBrandAttributesRelationDTO addDto = new CategoryBrandAttributesRelationDTO();
                    addDto.setId(ymlConfig.getPkId());
                    addDto.setCategoryId(byId.getId());
                    addDto.setBrandId(dto.getBrandId());
                    if (StringUtils.isNotBlank(dto.getSpecificationIds())) {
                        addDto.setSpecificationIds(getIds(dto.getSpecificationIds()));
                    }
                    if (StringUtils.isNotBlank(dto.getParamIds())) {
                        addDto.setParamIds(getIds(dto.getParamIds()));
                    }
                    if (StringUtils.isNotBlank(dto.getUnitIds())) {
                        addDto.setUnitIds(getIds(dto.getUnitIds()));
                    }
                    if (StringUtils.isNotBlank(dto.getLabelIds())) {
                        addDto.setLabelIds(getIds(dto.getLabelIds()));
                    }
                    categoryBrandAttributesRelationService.insert(addDto);
                } else {
                    CategoryBrandAttributesRelationDTO updateDTO = new CategoryBrandAttributesRelationDTO();
                    updateDTO.setId(relationDTO.getId());
                    if (StringUtils.isNotBlank(dto.getSpecificationIds())) {
                        String idsChange = this.checkIdsChange(dto.getSpecificationIds(), relationDTO.getSpecificationIds());
                        updateDTO.setSpecificationIds(idsChange);
                    }
                    if (StringUtils.isNotBlank(dto.getParamIds())) {
                        String idsChange = this.checkIdsChange(dto.getParamIds(), relationDTO.getParamIds());
                        updateDTO.setParamIds(idsChange);
                    }
                    if (StringUtils.isNotBlank(dto.getUnitIds())) {
                        String idsChange = this.checkIdsChange(dto.getUnitIds(), relationDTO.getUnitIds());
                        updateDTO.setUnitIds(idsChange);
                    }
                    if (StringUtils.isNotBlank(dto.getLabelIds())) {
                        String idsChange = this.checkIdsChange(dto.getLabelIds(), relationDTO.getLabelIds());
                        updateDTO.setLabelIds(idsChange);
                    }
                    categoryBrandAttributesRelationService.updateById(updateDTO);
                }

            }
        }
        //重新获取类目树放进redis
        List<CommodityCategoryTreeVO> categoryTree = this.queryCategoryTree();
        if (!isNull(categoryTree)) {
            //重新放入redis
            Object treeObject = JSONObject.toJSON(categoryTree);
            redisUtil.set(CATEGORY_REDIS_KEY, treeObject);
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * description: 封装一级类目和子集
     * param: [commodityCategoryTreeVOList, selectCommodityCategoryDTOList]
     * author: chenyu.wang
     * date: 2020-08-04
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> builCategoryTreeBySelectCategoryId(List<CommodityCategoryTreeVO> commodityCategoryTreeVOList, List<CommodityCategoryDTO> selectCommodityCategoryDTOList) {
        List<CommodityCategoryDTO> netxSelectCommodityCategoryDTOList = new ArrayList<>();
        for (CommodityCategoryDTO commodityCategoryDTO : selectCommodityCategoryDTOList) {
            List<CommodityCategoryDTO> commodityCategoryDTOS = this.queryByParentId(commodityCategoryDTO.getId());
            if (commodityCategoryDTOS.size() == 0) {
                continue;
            }
            for (CommodityCategoryDTO categoryDTO : commodityCategoryDTOS) {
                CommodityCategoryTreeVO tempCommodityCategoryTreeVO = new CommodityCategoryTreeVO();
                BeanUtils.copyProperties(categoryDTO, tempCommodityCategoryTreeVO);
                commodityCategoryTreeVOList.add(tempCommodityCategoryTreeVO);
                netxSelectCommodityCategoryDTOList.add(categoryDTO);
            }
            builCategoryTreeBySelectCategoryId(commodityCategoryTreeVOList, netxSelectCommodityCategoryDTOList);
        }
        return commodityCategoryTreeVOList;
    }

    /**
     * description: 根据父级id查询子集
     * param: [parentId]
     * author: chenyu.wang
     * date: 2020-08-04
     * return: java.util.List<com.ztgf.commodity.models.dto.CommodityCategoryDTO>
     */
    public List<CommodityCategoryDTO> queryByParentId(Long parentId) {
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO)
                .eq("is_publish", ONE)
                .eq("parent_id", parentId)
                .orderBy("sort", true);
        return this.selectList(wrapper);
    }


    /*
     * @description:更新其余类目序号 id:父级类目id,sort:原来的排序号，updateSort:要修改的排序号
     * @author: chenyu.wang
     * @date: 2020-09-17
     * @return:
     */
    private void getSort(Long id, Integer sort, Integer updateSort) {
        //查询是否存在要修改的排序号
        Wrapper<CommodityCategoryDTO> thisWrapper = new EntityWrapper<>();
        thisWrapper.eq("parent_id", id);
        thisWrapper.eq("sort", updateSort);
        thisWrapper.orderBy("sort", true);
        CommodityCategoryDTO thisOne = this.selectOne(thisWrapper);
        if (thisOne != null) {
            CommodityCategoryDTO updateDTO = new CommodityCategoryDTO();
            updateDTO.setId(thisOne.getId());
            updateDTO.setSort(sort);
            this.updateById(updateDTO);
        }
    }

    /**
     * @Description: 新增类目时重新排列排序号
     * @Author: WangChenYu
     * @Param: [id, sort]
     * @Date: 2020-10-10 15:07
     */
    private void getAddSort(Long id, Integer sort) {
        //获取排序号是否存在
        Wrapper<CommodityCategoryDTO> maxWrapper = new EntityWrapper<>();
        maxWrapper.eq("parent_id", id);
        maxWrapper.eq("sort", sort);
        maxWrapper.orderBy("sort", true);
        CommodityCategoryDTO one = this.selectOne(maxWrapper);
        if (one != null) {
            //获取最大排序号
            Integer maxSort = baseMapper.getMaxSort(id);
            CommodityCategoryDTO updateDTO = new CommodityCategoryDTO();
            updateDTO.setId(one.getId());
            updateDTO.setSort(maxSort + 1);
            this.updateById(updateDTO);
        }
    }

    /**
     * @Description: 取出不同的属性ids
     * @Author: WangChenYu
     * @Param: [now, raw]
     * @Date: 2020-10-10 15:07
     */
    private String checkIdsChange(String now, String raw) {
        if (!StringUtils.isNotBlank(raw)) {
            return now;
        }
        //原来的
        String[] rawString = raw.split(",");
        Arrays.sort(rawString);
        List<String> rawList = new ArrayList<>(Arrays.asList(rawString));
        String rawReal = String.join(",", rawString);
        //现在的
        String[] nowString = now.split(",");
        Arrays.sort(nowString);
        List<String> nowList = new ArrayList<>(Arrays.asList(nowString));
        String nowReal = String.join(",", nowString);
        if (!nowReal.equals(rawReal) && nowReal.length() > rawReal.length()) {
            nowList.removeAll(rawList);//取出不同的
            rawList.addAll(nowList);
            String collect = String.join(",", rawList);
            String[] strings = collect.split(",");
            Arrays.sort(strings);
            return String.join(",", strings);
        } else {
            return raw;
        }
    }

    /**
     * @Description: 获取最终级类目
     * @Author: chenyu.wang
     * @Params: [list, list2]
     * @Date: 2020.11.10 16:13
     */
    public List<CommodityCategoryDTO> getAllFinalCategory(List<CommodityCategoryDTO> list, List<CommodityCategoryDTO> list2) {
        for (CommodityCategoryDTO dto : list) {
            Integer checkCategory = this.getCheckCategory(dto.getId());
            if (checkCategory == 0) {
                list2.add(dto);
            } else {
                Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("parent_id", dto.getId());
                List<CommodityCategoryDTO> selectList = this.selectList(wrapper);
                if (isNull(selectList)) {
                    continue;
                }
                this.getAllFinalCategory(selectList, list2);
            }
        }
        return list2;
    }
}
